<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.connecting {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        #messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            background-color: #f8f9fa;
            font-family: monospace;
            font-size: 12px;
        }
        .message {
            margin-bottom: 5px;
            padding: 5px;
            border-radius: 3px;
        }
        .message.sent {
            background-color: #e3f2fd;
        }
        .message.received {
            background-color: #f3e5f5;
        }
        .message.system {
            background-color: #fff3e0;
            font-style: italic;
        }
    </style>
</head>
<body>
    <h1>WebSocket 连接测试</h1>
    
    <div class="container">
        <h3>连接配置</h3>
        <div class="input-group">
            <label for="serverUrl">服务器地址:</label>
            <input type="text" id="serverUrl" value="ws://localhost:8000/ws" placeholder="ws://localhost:8000/ws">
        </div>
        <div class="input-group">
            <label for="jwtToken">JWT Token:</label>
            <input type="text" id="jwtToken" placeholder="请输入JWT Token">
        </div>
        <div class="input-group">
            <div id="connectionStatus" class="status disconnected">未连接</div>
        </div>
        <button id="connectBtn" onclick="connect()">连接</button>
        <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
    </div>

    <div class="container">
        <h3>消息测试</h3>
        <div class="input-group">
            <label for="messageInput">发送消息:</label>
            <textarea id="messageInput" rows="3" placeholder="输入要发送的消息（JSON格式）">{\"type\": \"ping\", \"data\": \"hello\"}</textarea>
        </div>
        <button id="sendBtn" onclick="sendMessage()" disabled>发送消息</button>
        <button onclick="clearMessages()">清空消息</button>
    </div>

    <div class="container">
        <h3>消息日志</h3>
        <div id="messages"></div>
    </div>

    <div class="container">
        <h3>使用说明</h3>
        <ol>
            <li><strong>获取JWT Token:</strong> 首先需要通过登录接口获取有效的JWT Token</li>
            <li><strong>连接WebSocket:</strong> 输入JWT Token后点击"连接"按钮</li>
            <li><strong>发送消息:</strong> 连接成功后可以发送JSON格式的消息进行测试</li>
            <li><strong>查看日志:</strong> 所有发送和接收的消息都会显示在消息日志中</li>
        </ol>
        <h4>常用测试Token:</h4>
        <p>可以使用压测生成的JWT Token文件中的任意一个Token进行测试</p>
    </div>

    <script>
        let ws = null;
        let isConnecting = false;

        function updateStatus(status, message) {
            const statusDiv = document.getElementById('connectionStatus');
            statusDiv.className = `status ${status}`;
            statusDiv.textContent = message;
        }

        function addMessage(type, content) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            const timestamp = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `<strong>[${timestamp}] ${type.toUpperCase()}:</strong> ${content}`;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function connect() {
            if (isConnecting || (ws && ws.readyState === WebSocket.OPEN)) {
                return;
            }

            const serverUrl = document.getElementById('serverUrl').value;
            const jwtToken = document.getElementById('jwtToken').value;

            if (!jwtToken.trim()) {
                alert('请输入JWT Token');
                return;
            }

            isConnecting = true;
            updateStatus('connecting', '正在连接...');
            document.getElementById('connectBtn').disabled = true;

            // 构建WebSocket URL，将token作为查询参数
            const wsUrl = `${serverUrl}?token=${encodeURIComponent(jwtToken)}`;
            
            try {
                ws = new WebSocket(wsUrl);

                ws.onopen = function(event) {
                    isConnecting = false;
                    updateStatus('connected', '已连接');
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    document.getElementById('sendBtn').disabled = false;
                    addMessage('system', 'WebSocket连接已建立');
                };

                ws.onmessage = function(event) {
                    addMessage('received', event.data);
                };

                ws.onclose = function(event) {
                    isConnecting = false;
                    updateStatus('disconnected', `连接已关闭 (代码: ${event.code})`);
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('sendBtn').disabled = true;
                    addMessage('system', `WebSocket连接已关闭，代码: ${event.code}, 原因: ${event.reason || '未知'}`);
                    ws = null;
                };

                ws.onerror = function(error) {
                    isConnecting = false;
                    updateStatus('disconnected', '连接错误');
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('sendBtn').disabled = true;
                    addMessage('system', `WebSocket错误: ${error}`);
                };

            } catch (error) {
                isConnecting = false;
                updateStatus('disconnected', '连接失败');
                document.getElementById('connectBtn').disabled = false;
                addMessage('system', `连接异常: ${error.message}`);
            }
        }

        function disconnect() {
            if (ws) {
                ws.close();
            }
        }

        function sendMessage() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                alert('WebSocket未连接');
                return;
            }

            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();

            if (!message) {
                alert('请输入消息内容');
                return;
            }

            try {
                // 验证是否为有效JSON
                JSON.parse(message);
                ws.send(message);
                addMessage('sent', message);
                messageInput.value = '';
            } catch (error) {
                alert('消息格式错误，请输入有效的JSON格式');
            }
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
        }

        // 页面加载时的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 回车发送消息
            document.getElementById('messageInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && e.ctrlKey) {
                    sendMessage();
                }
            });
        });
    </script>
</body>
</html>